package com.ifast.news.controller;

import java.util.Arrays;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.annotation.Log;
import com.ifast.common.annotation.OperateRecord;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.service.DictService;
import com.ifast.common.utils.Const;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.alioss.OSSBjOtherClientUtil;
import com.ifast.common.utils.alioss.UploadResult;
import com.ifast.news.domain.News;
import com.ifast.news.service.NewsService;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.filter.SameUrlData;
import com.luculent.util.extension.api.DataResult;

/**
 * 新闻管理
 * @author shíQíang㊚
 * @date 2019年4月9日10:05:14
 */
@RequestMapping("/news/manage")
@Controller
public class NewsController extends AdminBaseController {
	
    private String preHtml = "lucky/news/manage/";
    
    @Autowired
    private NewsService newsService; 
    @Autowired
    private DictService sysDictService;
    
    @Log("进入管理页面")
    @GetMapping()
    @RequiresPermissions("news:manage:info")
    String newsText(Model model){ 
        return preHtml+ "qy_list_text";
    }
    
    @Log("进入管理页面")
    @GetMapping("picture") 
    @RequiresPermissions("news:manage:info")
    String newsPicture(Model model){
        return preHtml+ "qy_list_picture";
    }  
   
    @Log("进入管理页面")
    @GetMapping("video") 
    @RequiresPermissions("news:manage:info")
    String vido(Model model){
        return preHtml+ "qy_list_video";
    }
    
    
    @GetMapping("qyListDataText") 
    @OperateRecord(OperateName = "文本新闻列表",ModellName ="新闻模块")
    @ResponseBody 
    @Log("列表")
    public Result<Page<News>> qyListDataText(Model model,News explain) {
    	return newsList(Const.newsType.news_type_text.getId(),explain); 
    }
    
    @GetMapping("qyListDataPicture") 
    @OperateRecord(OperateName = "图片新闻列表",ModellName ="新闻模块")
    @ResponseBody 
    @Log("列表")
    public Result<Page<News>> qyListDataPicture(Model model,News explain) { 
        return newsList(Const.newsType.news_type_picture.getId(),explain);
    }
    
    @GetMapping("qyListDataVideo") 
    @OperateRecord(OperateName = "视频新闻列表",ModellName ="新闻模块")
    @ResponseBody 
    @Log("列表")
    public Result<Page<News>> qyListDataVideo(Model model,News explain) { 
        return newsList(Const.newsType.news_type_video.getId(),explain);
    }
    
    private Result<Page<News>> newsList(String id,News explain){
    	 Page<News> page = this.newsService.selectPage(getPage(News.class),new EntityWrapper<News>() 
         		.like("DW_CODE", this.getUser().getDwCode(), SqlLike.RIGHT)
         		.eq("CATEGORY",id)
         		.ne("DELFLAG","1")
         		.eq(StringUtils.isNotBlank(explain.getClassify()),"CLASSIFY",explain.getClassify())
         		.like(StringUtils.isNotBlank(explain.getTitle()), "TITLE", explain.getTitle())
         		.orderBy("top").orderBy("sort").orderBy("create_time",false));
         Optional.ofNullable(page.getRecords()).ifPresent(infos -> infos.parallelStream().forEach(info -> {
         	info.setClassifyName(sysDictService.selectById(info.getClassify()).getName());
//         	if(StringUtils.isBlank(info.getUrl())){
//         		info.setUrl("/img/a1.jpg");
//         	}
         })); 
         return Result.ok(page);
    }
    
    @Log("相册列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("news:manage:list")
    public Result<Page<News>> list(Integer pageNumber, Integer pageSize, News fileDTO) {
        // 查询列表数据
        Page<News> page = getPage(News.class); 
        page = newsService.selectPage(page, new EntityWrapper<News>(fileDTO).orderBy("CREATE_TIME", false).orderBy("UPDATE_TIME", false));
//        Optional.ofNullable(page.getRecords()).ifPresent(photos -> photos.parallelStream().forEach(photo -> photo.setPhotoMsg(albumPhotoMsgService.selectById(photo.getMsgId()).getMsg())));
        return Result.ok(page);
    } 
    
    /**
     *  
     * @param model
     * @param id 
     */
    @GetMapping("/addText")
    @RequiresPermissions("news:manage:add")
    public String addText(Model model, String id){
    	model.addAttribute("addText",Const.newsType.news_type_text.getId()).addAttribute("addPicture",Const.newsType.news_type_picture.getId());
        return  preHtml+"add_text";
    }
    
    @GetMapping("/addPicture")
    @RequiresPermissions("news:manage:add")
    public String addPicture(Model model, String id){
    	model.addAttribute("addText",Const.newsType.news_type_text.getId()).addAttribute("addPicture",Const.newsType.news_type_picture.getId());
        return  preHtml+"add_picture";
    }
    
    @GetMapping("/addVideo")
    @RequiresPermissions("news:manage:add")
    public String addVideo(Model model, String id){
    	model.addAttribute("addText",Const.newsType.news_type_text.getId()).addAttribute("addPicture",Const.newsType.news_type_picture.getId());
        return  preHtml+"add_video";
    }
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/editText/{id}")
    @RequiresPermissions("news:manage:edit")
    public String editText(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"edit_text";
    } 
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/editPicture/{id}")
    @RequiresPermissions("news:manage:edit")
    public String edit(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"edit_picture";
    }
    /**
     * 查看
     * @param model
     * @param id 
     */
    @GetMapping("/viewText/{id}")
    @RequiresPermissions("news:manage:view")
    public String viewText(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"view_text";
    } 
    /**
     * 查看
     * @param model
     * @param id 
     */
    @GetMapping("/viewPicture/{id}")
    @RequiresPermissions("news:manage:view")
    public String view(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"view_picture";
    } 
    
    /**
     * 编辑
     * @param model
     * @param id 
     */
    @GetMapping("/editVideo/{id}")
    @RequiresPermissions("news:manage:edit")
    public String editVideo(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"edit_video";
    }
    /**
     * 查看
     * @param model
     * @param id 
     */
    @GetMapping("/viewVideo/{id}")
    @RequiresPermissions("news:manage:view")
    public String viewVideo(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",newsService.selectById(id));
        return  preHtml+"view_video";
    } 
    /**
   	 * 视频上传
   	 * 
   	 * @param request
   	 * @return
   	 */
   	@RequestMapping(value="/uploadvideo")
   	@ResponseBody 
   	public UploadResult uploadVideo(HttpServletRequest request) {
   		OSSBjOtherClientUtil ossClientUtil = OSSBjOtherClientUtil.getInstance();
   		UploadResult ur = ossClientUtil.uploadImg2OssMoreFile(request, "news/video/yuan");
   		if(ur!=null && ur.getFileURLs()!=null && ur.getFileURLs().size()>0){
   			ur.getFileURLs().add(ur.getFileURLs().get(0).split("\\?")[0]+"?x-oss-process=video/snapshot,t_10000,m_fast");
   		}  
   		return ur;
   	}
   	
   	@RequestMapping(value="/zhuanma")
	@ResponseBody
	public Result<?> zhuanma(String id){
   		return this.newsService.transCode(id); 
	}
   	
    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @Log("删除")
    @RequiresPermissions("news:manage:remove")
    public Result<?> remove(Model model,String id){  
        return  Result.CODE_SUCCESS.equals(newsService.remove(id).getCode()) ? Result.ok():Result.fail();
    }
    
    /**
     * 批量删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("news:manage:batchRemove")
    @Log("批量删除")
    public Result<?> batchRemove(@RequestParam("ids[]") String[] ids) {
    	try { 
            return Result.CODE_SUCCESS.equals(newsService.batchRemove(Arrays.asList(ids)).getCode()) ? Result.ok():Result.fail();
		} catch (Exception e) {
			log.error(e.toString(),e);
			return Result.fail();
		} 
    } 
    
    /**
     * 保存 
     */
    @PostMapping("/save")
    @ResponseBody
    @SameUrlData
    @OperateRecord(OperateName = "保存新闻",ModellName ="新闻管理")
    public Result<?> save(HttpServletRequest request,News news) {
        try{ 
        	UserDO user = this.getUser(); 
        	return Result.CODE_SUCCESS.equals(newsService.add(request,user.getId().toString(),user.getDwCode(),news).getCode()) ? Result.ok():Result.fail();
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    } 
    
}